const { asyncHandler } = require('../middleware/errorHandler');
const { success, error, paginate, paginateResponse, encryptPassword } = require('../utils/common');
const User = require('../models/User');
const StudentLesson = require('../models/StudentLesson');
const { Op } = require('sequelize');
const logger = require('../utils/logger');

class StudentController {
  /**
   * 新增学生
   */
  static createStudent = asyncHandler(async (req, res) => {
    const { 
      username, 
      password, 
      email, 
      lesson_fee = 0, 
      nickname, 
      status = 'active', 
      remark,
      gender = 'unknown',
      total_lessons = 0
    } = req.body;

    // 验证必填字段
    if (!username) {
      return res.status(400).json(error('用户名为必填项'));
    }

    // 检查用户名是否已存在
    const existingUser = await User.findOne({
      where: {
        [Op.or]: [
          { username },
          ...(email ? [{ email }] : [])
        ]
      }
    });

    if (existingUser) {
      return res.status(400).json(error('用户名或邮箱已存在'));
    }

    // 加密密码（如果提供了密码）
    let hashedPassword = null;
    if (password) {
      hashedPassword = await encryptPassword(password);
    }

    // 创建学生
    const studentData = {
      username,
      email,
      lesson_fee: parseFloat(lesson_fee) || 0,
      nickname: nickname || username,
      role: 'student',
      status,
      remark,
      gender,
      total_lessons: parseInt(total_lessons) || 0,
      used_lessons: 0
    };

    // 如果提供了密码，则添加到数据中
    if (hashedPassword) {
      studentData.password = hashedPassword;
    }

    const student = await User.create(studentData);

    logger.info(`管理员创建学生: ${student.id}`);

    res.json(success(student, '学生创建成功'));
  });

  /**
   * 获取学生列表
   */
  static getStudents = asyncHandler(async (req, res) => {
    const { 
      page = 1, 
      limit = 10, 
      keyword,
      sort = 'created_at',
      order = 'desc'
    } = req.query;

    const { offset, limit: pageLimit } = paginate(page, limit);

    // 构建查询条件
    const where = {
      role: 'student',
      is_deleted: false
    };
    
    
    if (keyword) {
      where[Op.or] = [
        { username: { [Op.like]: `%${keyword}%` } },
        { nickname: { [Op.like]: `%${keyword}%` } },
        { email: { [Op.like]: `%${keyword}%` } }
      ];
    }

    // 构建排序条件
    const orderClause = [[sort, order.toUpperCase()]];

    // 查询学生
    const { count, rows: students } = await User.findAndCountAll({
      where,
      attributes: [
        'id', 'username', 'nickname', 'email', 'lesson_fee', 'avatar',
        'status', 'level', 'experience', 'coin', 'created_at',
        'last_login_at', 'last_login_ip', 'gender', 'total_lessons', 'used_lessons'
      ],
      order: orderClause,
      offset,
      limit: pageLimit
    });

    res.json(paginateResponse(students, count, page, limit));
  });

  /**
   * 获取学生详情
   */
  static getStudentDetail = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const student = await User.findOne({
      where: { id, role: 'student' },
      attributes: [
        'id', 'username', 'nickname', 'email', 'lesson_fee', 'avatar',
        'bio', 'gender', 'birthday', 'address',
        'status', 'level', 'experience', 'coin', 'votes', 'sign',
        'created_at', 'last_login_at', 'last_login_ip',
        'total_lessons', 'used_lessons', 'remark'
      ]
    });

    if (!student) {
      return res.status(404).json(error('学生不存在'));
    }

    res.json(success(student, '获取成功'));
  });

  /**
   * 更新学生信息
   */
  static updateStudent = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { 
      nickname, 
      email, 
      lesson_fee, 
      status, 
      gender, 
      total_lessons,
      remark 
    } = req.body;

    // 验证学生是否存在
    const student = await User.findOne({
      where: { id, role: 'student' }
    });

    if (!student) {
      return res.status(404).json(error('学生不存在'));
    }

    // 检查邮箱是否已被其他用户使用
    if (email && email !== student.email) {
      const existingUser = await User.findOne({
      where: { 
          email, 
          id: { [Op.ne]: id } 
        }
      });

      if (existingUser) {
        return res.status(400).json(error('邮箱已被其他用户使用'));
      }
    }

    // 更新学生信息
    const updateData = {};
    if (nickname !== undefined) updateData.nickname = nickname;
    if (email !== undefined) updateData.email = email;
    if (lesson_fee !== undefined) updateData.lesson_fee = parseFloat(lesson_fee) || 0;
    if (status !== undefined) updateData.status = status;
    if (gender !== undefined) updateData.gender = gender;
    if (total_lessons !== undefined) updateData.total_lessons = parseInt(total_lessons) || 0;
    if (remark !== undefined) updateData.remark = remark;

    await student.update(updateData);

    logger.info(`管理员更新学生信息: ${id}`);

    res.json(success(student, '学生信息更新成功'));
  });

  /**
   * 获取学生课时记录
   */
  static getStudentLessons = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { page = 1, limit = 10 } = req.query;

    const { offset, limit: pageLimit } = paginate(page, limit);

    // 验证学生是否存在
    const student = await User.findOne({
      where: { id, role: 'student' }
    });

    if (!student) {
      return res.status(404).json(error('学生不存在'));
    }

    // 查询学生的课时记录
    const { count, rows: lessons } = await StudentLesson.findAndCountAll({
      where: { student_id: id },
      order: [['lesson_date', 'DESC']],
      offset,
      limit: pageLimit
    });

    // 计算统计信息
    const totalLessons = count;
    const totalDuration = lessons.reduce((sum, lesson) => sum + (lesson.duration || 0), 0);
    const remainingLessons = parseFloat((student.total_lessons - student.used_lessons).toFixed(2));

    // 返回课时记录和统计信息
    const responseData = {
      list: lessons,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      student: {
        id: student.id,
        username: student.username,
        nickname: student.nickname,
        total_lessons: student.total_lessons,
        used_lessons: student.used_lessons,
        remaining_lessons: remainingLessons
      },
      stats: {
        totalLessons,
        totalDuration,
        remainingLessons
      }
    };

    res.json(success(responseData, '获取成功'));
  });

  /**
   * 添加学生课时记录
   */
  static addStudentLesson = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { 
      lesson_title, 
      lesson_date, 
      duration, 
      replay_url, 
      notes 
    } = req.body;

    // 验证必填字段
    if (!lesson_title || !lesson_date || !duration) {
      return res.status(400).json(error('课程标题、上课日期和时长为必填项'));
    }

    // 验证学生是否存在
    const student = await User.findOne({
      where: { id, role: 'student' }
    });

    if (!student) {
      return res.status(404).json(error('学生不存在'));
    }

    // 检查剩余课时
    const remainingLessons = parseFloat((student.total_lessons - student.used_lessons).toFixed(2));
    if (remainingLessons <= 0) {
      return res.status(400).json(error('学生课时不足，无法添加课时记录'));
    }


    // 创建课时记录
    const lesson = await StudentLesson.create({
      student_id: id,
      lesson_title,
      lesson_date: new Date(lesson_date),
      duration: parseInt(duration),
      replay_url,
      notes,
      created_by: req.user?.id || 1 // 如果禁用了auth，使用默认管理员ID
    });

    await this.calculateUsedLessons(id);
    logger.info(`管理员为学生 ${id} 添加课时记录: ${lesson.id}`);

    res.json(success(lesson, '课时记录添加成功'));
  });

  /**
   * 更新学生课时记录
   */
  static updateStudentLesson = asyncHandler(async (req, res) => {
    const { id, lesson_id } = req.params;
    const { 
      lesson_title, 
      lesson_date, 
      duration, 
      replay_url, 
      notes 
    } = req.body;

    // 验证学生是否存在
    const student = await User.findOne({
      where: { id, role: 'student' }
    });

    if (!student) {
      return res.status(404).json(error('学生不存在'));
    }

    // 查找课时记录
    const lesson = await StudentLesson.findOne({
      where: { id: lesson_id, student_id: id }
    });

    if (!lesson) {
      return res.status(404).json(error('课时记录不存在'));
    }
    // 更新课时记录
    await lesson.update({
      lesson_title,
      lesson_date: lesson_date ? new Date(lesson_date) : lesson.lesson_date,
      duration: duration ? parseInt(duration) : lesson.duration,
      replay_url,
      notes
    });

    await this.calculateUsedLessons(id);

    logger.info(`管理员更新学生 ${id} 的课时记录: ${lesson_id}`);

    res.json(success(lesson, '课时记录更新成功'));
  });

  /**
   * 删除学生课时记录
   */
  static deleteStudentLesson = asyncHandler(async (req, res) => {
    const { id, lesson_id } = req.params;

    // 验证学生是否存在
    const student = await User.findOne({
      where: { id, role: 'student' }
    });

    if (!student) {
      return res.status(404).json(error('学生不存在'));
    }

    // 查找课时记录
    const lesson = await StudentLesson.findOne({
      where: { id: lesson_id, student_id: id }
    });

    if (!lesson) {
      return res.status(404).json(error('课时记录不存在'));
    }

    // 计算要减少的课时数（按小时计算）
    const consumedLessons = parseFloat((parseInt(lesson.duration) / 60).toFixed(2));

    // 删除课时记录
    await lesson.destroy();

    await this.calculateUsedLessons(id);

    logger.info(`管理员删除学生 ${id} 的课时记录: ${lesson_id}`);

    res.json(success(null, '课时记录删除成功'));
  });

  /**
   * 更新学生课时数量
   */
  static updateStudentLessons = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { total_lessons } = req.body;

    if (total_lessons === undefined || total_lessons < 0) {
      return res.status(400).json(error('课时数量不能为负数'));
    }

    // 验证学生是否存在
    const student = await User.findOne({
      where: { id, role: 'student' }
    });

    if (!student) {
      return res.status(404).json(error('学生不存在'));
    }

    // 更新课时数量
    await student.update({
      total_lessons: parseInt(total_lessons)
    });

    logger.info(`管理员更新学生 ${id} 的课时数量: ${total_lessons}`);

    res.json(success(student, '课时数量更新成功'));
  });

  /**
   * 删除学生
   */
  static deleteStudent = asyncHandler(async (req, res) => {
    const { id } = req.params;
    // 查找学生
    const student = await User.findOne({ where: { id, role: 'student' } });
    if (!student) {
      return res.status(404).json(error('学生不存在'));
    }
    await student.update({
      is_deleted: true
    });
    logger.info(`管理员删除学生: ${id}`);
    res.json(success(null, '学生删除成功'));
  });

  static calculateUsedLessons = async (id) => {

    const student = await User.findOne({ where: { id, role: 'student' } });
    if (!student) {
      return;
    }
    const lessons = await StudentLesson.findAll({
      where: {
        student_id: id,
      }})
    const used_lessons = lessons.reduce((sum, lesson) => sum - 0 + (lesson.duration || 0), 0);
    const consumedLessons = parseFloat((used_lessons) / 60);
    await student.update({
      used_lessons: consumedLessons
    });
  };
}

module.exports = StudentController; 